package com.zsc.oj.aop;

import com.zsc.oj.annotation.AuthCheck;
import com.zsc.oj.common.ErrorCode;
import com.zsc.oj.exception.BusinessException;
import com.zsc.oj.model.entity.User;
import com.zsc.oj.model.enums.UserRoleEnum;
import com.zsc.oj.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 权限校验 AOP
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 当前登录用户
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        // 不需要权限，放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 必须有该权限才通过
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 如果被封号，直接拒绝
        if (UserRoleEnum.BAN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 必须有管理员权限
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum)) {
            // 用户没有管理员权限，拒绝
            if (!UserRoleEnum.ADMIN.equals(userRoleEnum)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }

    /**
     * 默认的保存日志方法
     *
     * @param joinPoint 切入点
     * @param time      耗时
     * @param status    请求状态
     * @param result    返回参数
     * @throws NoSuchMethodException 异常
     */
//    private void saveLogDef(ProceedingJoinPoint joinPoint, long time, boolean status, String result) throws NoSuchMethodException, IOException {
//        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//        Method method = joinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), signature.getParameterTypes());
//        //获取到注解类
//        LogOperation annotation = method.getAnnotation(LogOperation.class);
//        // 组装日志
//        WebApiLogEntity entity = new WebApiLogEntity();
//        entity.setLogTime(new Date());
//        entity.setModuleName(modelName);
//        if (annotation != null) {
//            //注解上的描述
//            entity.setApi(annotation.value());
//        }
//        // 耗时
//        entity.setCostTime(time);
//        // 状态
//        entity.setStatus(status);
//        //请求相关信息
//        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//        if (null != request) {
//            entity.setIpAddr(HttpContextUtils.getRealIp(request));
//            String header = HttpContextUtils.getAllHeader(request);
//            entity.setHeader(limitLen(header));
//            entity.setRequestUri(limitLen(request.getRequestURI()));
//            entity.setMethod(request.getMethod());
//        }
//        // 请求参数
//        try {
//            String args = getArgs(joinPoint);
//            entity.setArgs(limitLen(args, 2048));
//            log.info("args : {}", args);
//        } catch (Exception e) {
//            log.error("参数序列错误：", e);
//            e.printStackTrace();
//        }
//        // 返回参数
//        if (null != result) {
//            entity.setResult(limitLen(result, 2048));
//            log.info("result : {}", result);
//        }
//        apiLogService.saveLog(entity);
//    }
}

